/*Copyright (c) 2012 Nicolás Zalaquett

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice
shall be included in all copies or substantial portions of
the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/
package extrae;

import javafx.scene.CustomNode;
import javafx.scene.Node;
import javafx.scene.Group;
import javafx.scene.chart.ScatterChart.Data;
import javafx.scene.chart.ScatterChart.Series;
import javafx.util.Math;
import javafx.scene.control.ChoiceBox;
import javafx.scene.input.MouseEvent;
import extrae.selectorSensores.sensorNodeAN;
import javax.swing.JOptionPane;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.scene.control.ToggleButton;
import javafx.scene.Cursor;
import extrae.selectorSensores.sensorAN;
import javafx.scene.control.Label;
import extrae.selectorSensores.sensorDIG;
import javafx.scene.layout.LayoutInfo;

/**
 * @author lojkoro
 */

/*GaficoNode: Clase para graficar y analizar los datos obtenidos.
 *Incluye funciones de desplazamiento, zoom y ajuste lineal.
 *TODO: Mejorar gráfico digital, mostrar chi^2, incluir series, asociar
 *a tabla, opción de exportación a jpg, guardar, abrir, imprimir, etc...*/
public class GraficoNode extends CustomNode {    
    public var Medicion: MedicionAnaloga = MedicionAnaloga {};
    public var MedicionDig: MedicionDigital = MedicionDigital {};
    public var titulo: String;
    public var Datos: Data[];
    public var DatosTotales: Data[];
    ///QUEDAN TODAVIA SON DE LOS SELECTORES DE EJES
    public var xMouse: Number;
    public var yMouse: Number;
    public var conversorCanalIndice: Integer[] = [0, 1, 2, 3];
    public var xInt: Integer;
    public var yInt: Integer;
    public var nolohice: Boolean = true;
    //////////////////////////////
    public var zona: Rectangle = Rectangle { fill: Color.BLACK
                height: bind medidasZona[0]
                width: bind medidasZona[1]
                layoutX: 0
                layoutY: 0
                visible: false
                opacity: 0.2 };
    public var medidasZona: Number[] = [0.0, 0.0];
    public var AxUB:Number;
    public var AxLB:Number;
    public var AyUB:Number;
    public var AyLB:Number;
    public var valoresPosicionActual:Number[]=[0.0,0.0];
    public var valoresPosicionInicial:Number[]=[0.0,0.0];
    public var infoPuntero:Label=Label{
        layoutX: bind (scene.width-infoPuntero.width-10)
        layoutY: bind (scene.height-infoPuntero.height-5)
        text:bind "x : {%.6f valoresPosicionActual[0]} \ny : {%.6f valoresPosicionActual[1]}"
        visible:true
        };
    public var constantesAjuste: Double[]=[0.0,0.0];
    var existeAjuste: Boolean = false;
    public var DatosAjuste: javafx.scene.chart.LineChart.Data[];
    public var detallesAjuste:Label=Label{
        layoutX: bind (scatterChart.width-detallesAjuste.width-10)
        layoutY: 30
        text:bind "Ecuación de Ajuste : Y = {%.6f constantesAjuste[1]} X + {%.6f constantesAjuste[0]}"
        visible:false
    }
    public var numberAxisX: javafx.scene.chart.part.NumberAxis = javafx.scene.chart.part.NumberAxis {
                lowerBound: 0
                upperBound: 10.0
                label: "x"
                minorTickCount: 5
                tickUnit: bind ((numberAxisX.upperBound - numberAxisX.lowerBound) / 5)
                formatTickLabel: function(value) {
                    "{%.2f value}"
                                                 }
            }
    public var numberAxisY: javafx.scene.chart.part.NumberAxis = javafx.scene.chart.part.NumberAxis {
                lowerBound: 0
                upperBound: 10.0
                label: "y"
                minorTickCount: 5
                tickUnit: bind ((numberAxisY.upperBound - numberAxisY.lowerBound) / 5)
                formatTickLabel: function(value) {
                                        "{%.2f value}"
                                                 }
            }
    public var numberAxisX2: javafx.scene.chart.part.NumberAxis = javafx.scene.chart.part.NumberAxis {
                lowerBound: bind numberAxisX.lowerBound
                upperBound: bind numberAxisX.upperBound
                label: "x"
                minorTickCount: 5
                tickUnit: bind numberAxisX.tickUnit
                axisStroke:Color.TRANSPARENT
                labelFill:Color.TRANSPARENT
                tickLabelFill:Color.TRANSPARENT
                tickMarkStroke:Color.TRANSPARENT
                formatTickLabel: function(value) {
                                        "{%.2f value}"
                                                 }
            }
    public var numberAxisY2: javafx.scene.chart.part.NumberAxis = javafx.scene.chart.part.NumberAxis {
                lowerBound: bind numberAxisY.lowerBound
                upperBound: bind numberAxisY.upperBound
                label: "y"
                minorTickCount: 5
                tickUnit: bind numberAxisY.tickUnit
                axisStroke:Color.TRANSPARENT
                labelFill:Color.TRANSPARENT
                tickLabelFill:Color.TRANSPARENT
                tickMarkStroke:Color.TRANSPARENT
                formatTickLabel: function(value) {
                                        "{%.2f value}"
                                                 }
            }
    public var escalaEjeX=bind Math.abs((numberAxisX.upperBound - numberAxisX.lowerBound) / numberAxisX.width);
    public var escalaEjeY=bind Math.abs((numberAxisY.upperBound - numberAxisY.lowerBound) / numberAxisY.height);
    public var scatterChartSeries: Series = Series {
                name: bind titulo
                data: bind Datos
            }
    public var scatterChart: javafx.scene.chart.ScatterChart = javafx.scene.chart.ScatterChart {
                layoutX: 10.0
                layoutY: 40.0
                layoutInfo: LayoutInfo{
                                width: bind scene.width-30
                                height: bind (scene.height-50)
                            }
                title: bind titulo;
                data: [scatterChartSeries,]
                xAxis: numberAxisX
                yAxis: numberAxisY
                dataEffect: null
                legendVisible:false
                customBackgroundContent: Rectangle {
                    fill: Color.WHITESMOKE
                    height: bind numberAxisY.height
                    width: bind numberAxisX.width
                    layoutX: 0
                    layoutY: 0
                    pickOnBounds: true
                    blocksMouse:true
                    onMouseReleased: function(event): Void {
                        actualizarPos(event);
                        guardarValoresEjesParaDrag();
                        if(zona.visible){
                        zona.visible=false;
                        var parteX= valoresPosicionInicial[0];
                        var parteY= valoresPosicionInicial[1];
                        var terminaX= valoresPosicionActual[0];
                        var terminaY= valoresPosicionActual[1];
                        if(toggleZoom.selected){
                            if (event.dragX == 0 or event.dragY == 0) { } else {
                                    numberAxisX.upperBound = Math.max(parteX,terminaX);
                                    numberAxisX.lowerBound = Math.min(parteX,terminaX);
                                    numberAxisY.upperBound = Math.max(parteY,terminaY);
                                    numberAxisY.lowerBound = Math.min(parteY,terminaY);
                                Datos = [];
                                Datos=discriminadorDePuntos(DatosTotales,numberAxisX.lowerBound,numberAxisX.upperBound,numberAxisY.lowerBound,numberAxisY.upperBound);
                                insertarAjuste();
                            }
                        }
                        else if(toggleFit.selected){
                            //TODO: asegurar que esten ambos puntos en el grafico
                            if (event.dragX == 0 or event.dragY == 0) { }
                            else {
                                var minX=Math.min(parteX,terminaX);
                                var maxX=Math.max(parteX,terminaX);
                                var minY=Math.min(parteY,terminaY);
                                var maxY=Math.max(parteY,terminaY);
                                var DataAux:Data[]=discriminadorDePuntos(DatosTotales,minX,maxX,minY,maxY);
                                if(DataAux.size()>1){
                                    existeAjuste=true;
                                    obtener_ponerAjusteLineal(DataAux);
                                }
                                else{existeAjuste=false;
                                     detallesAjuste.visible=false;
                                     lineChart.data=[];}
                            }
                        }
                        }
                    }
                    onMouseWheelMoved: function(event):Void {
                            actualizarPos(event);
                            var distUBx=(1+Math.signum(event.wheelRotation)*0.1)*Math.abs((numberAxisX.upperBound-valoresPosicionActual[0]));
                            var distLBx=(1+Math.signum(event.wheelRotation)*0.1)*Math.abs((valoresPosicionActual[0]-numberAxisX.lowerBound));
                            var distUBy=(1+Math.signum(event.wheelRotation)*0.1)*Math.abs((numberAxisY.upperBound-valoresPosicionActual[1]));
                            var distLBy=(1+Math.signum(event.wheelRotation)*0.1)*Math.abs((valoresPosicionActual[1]-numberAxisY.lowerBound));
                            numberAxisX.upperBound=valoresPosicionActual[0]+distUBx;
                            numberAxisX.lowerBound=valoresPosicionActual[0]-distLBx;
                            numberAxisY.upperBound=valoresPosicionActual[1]+distUBy;
                            numberAxisY.lowerBound=valoresPosicionActual[1]-distLBy;
                            Datos = [];
                            Datos=discriminadorDePuntos(DatosTotales,numberAxisX.lowerBound,numberAxisX.upperBound,numberAxisY.lowerBound,numberAxisY.upperBound);
                            insertarAjuste();
                   }
                    onMouseDragged:function(event):Void{
                        actualizarPos(event);
                       if(toggleDesplazar.selected){
                            numberAxisX.upperBound=AxUB-event.dragX*escalaEjeX;
                            numberAxisX.lowerBound=AxLB-event.dragX*escalaEjeX;
                            numberAxisY.upperBound=AyUB+event.dragY*escalaEjeY;
                            numberAxisY.lowerBound=AyLB+event.dragY*escalaEjeY;
                            Datos = [];
                            Datos=discriminadorDePuntos(DatosTotales,numberAxisX.lowerBound,numberAxisX.upperBound,numberAxisY.lowerBound,numberAxisY.upperBound);
                            insertarAjuste();
                       }
                       else if(toggleZoom.selected or toggleFit.selected){
                            ajustarZona(event);
                       }
                   }
                    onMousePressed:function(event):Void{
                       actualizarPos(event);
                       valoresPosicionInicial[0]=valoresPosicionActual[0];
                       valoresPosicionInicial[1]=valoresPosicionActual[1];
                       guardarValoresEjesParaDrag();
                       if(toggleZoom.selected or toggleFit.selected){
                           medidasZona[0]=0.0;
                           medidasZona[1]=0.0;
                           zona.visible=true;
                            }
                       }
                    onMouseMoved:actualizarPos


                }//Rectangle

            }//ScatterChart
    public var lineChart: javafx.scene.chart.LineChart = javafx.scene.chart.LineChart{
                showSymbols:false
                layoutX: 10.0
                layoutY: 40.0
                layoutInfo: LayoutInfo{
                                width: bind scene.width-30
                                height: bind (scene.height-50)
                            }
                title: bind scatterChart.title
                data: []
                xAxis: numberAxisX2
                yAxis: numberAxisY2
                dataEffect: null
                verticalAlternateRowFill:Color.TRANSPARENT
                legendVisible:false
                plotBackgroundFill:Color.TRANSPARENT
                plotBackgroundStroke:Color.TRANSPARENT
                titleFill:Color.TRANSPARENT
                verticalGridLineStroke:Color.TRANSPARENT
                horizontalGridLineStroke:Color.TRANSPARENT
                blocksMouse:false
                customBackgroundContent: Rectangle { fill: Color.TRANSPARENT
                    height: bind numberAxisY.height
                    width: bind numberAxisX.width
                    layoutX: 0
                    layoutY: 0
                    //pickOnBounds: true
                    }

            }
    public function actualizarPos(event:MouseEvent):Void{
                        valoresPosicionActual[0]=event.x*escalaEjeX+numberAxisX.lowerBound;
                        valoresPosicionActual[1]=(numberAxisY.height-event.y)*escalaEjeY+numberAxisY.lowerBound;}
    public function ajustarZona(event:MouseEvent):Void{
        if(event.dragX<0){zona.layoutX=event.dragAnchorX+event.dragX;}
                            else{zona.layoutX=event.dragAnchorX;}
                            if(event.dragY<0){zona.layoutY=event.dragAnchorY+event.dragY;}
                            else{zona.layoutY=event.dragAnchorY;}
                            medidasZona[0]=Math.abs(event.dragY);
                            medidasZona[1]=Math.abs(event.dragX);
    }
    public function guardarValoresEjesParaDrag():Void{
                       AxUB=numberAxisX.upperBound;
                       AxLB=numberAxisX.lowerBound;
                       AyUB=numberAxisY.upperBound;
                       AyLB=numberAxisY.lowerBound;
        }
    public function discriminadorDePuntos(d:Data[],minX:Number,maxX:Number,minY:Number,maxY:Number):Data[]{
        var dataAux:Data[]=[];
        for(dat in d){
                                 if (dat.xValue >= minX and dat.xValue <=maxX and dat.yValue >= minY and dat.yValue <= maxY){
                                        insert dat into dataAux;}
                                }
        return dataAux;
    }
    public function obtener_ponerAjusteLineal(d:Data[]):Void{
                                    var n=d.size();
                                    var sX:Double=0.0;
                                    var sY:Double=0.0;
                                    var sYX:Double=0.0;
                                    var sXX:Double=0.0;
                                    for(dat in d){
                                        sX+=dat.xValue;
                                        sY+=dat.yValue;
                                        sYX+=dat.xValue * dat.yValue;
                                        sXX+=Math.pow(dat.xValue,2);
                                    }
                                    var b=(n * sYX - sX * sY)/(n * sXX - Math.pow(sX,2));
                                    var a=(sY - sX * b)/n;
                                    constantesAjuste[0]=a;
                                    constantesAjuste[1]=b;
                                    insertarAjuste();
                                    detallesAjuste.visible=true;
    }
    public function insertarAjuste(){
        if(existeAjuste){
        var minX:Number=numberAxisX.lowerBound;
        var maxX:Number=numberAxisX.upperBound;
        var miX:Number=minX;
        var maX:Number=maxX;
        var miY:Number=numberAxisY.lowerBound;
        var maY:Number=numberAxisY.upperBound;
        var do=1;
        if((miX*constantesAjuste[1]+constantesAjuste[0])<=miY){
            miX=(miY-constantesAjuste[0])/constantesAjuste[1];
            if(miX<minX)
            {do=0;}
            }
        else if((miX*constantesAjuste[1]+constantesAjuste[0])>=maY){
            miX=(maY-constantesAjuste[0])/constantesAjuste[1];
            if(miX<minX)
            {do=0;}
            }
        if((maX*constantesAjuste[1]+constantesAjuste[0])<=miY){
            maX=(miY-constantesAjuste[0])/constantesAjuste[1];
            if(maX>maxX)
            {do=0;}
            }
        else if((maX*constantesAjuste[1]+constantesAjuste[0])>=maY){
            maX=(maY-constantesAjuste[0])/constantesAjuste[1];
            if(maX>maxX)
            {do=0;}
            }

        DatosAjuste=[];
        insert javafx.scene.chart.LineChart.Data{xValue:miX yValue:(miX*constantesAjuste[1]+constantesAjuste[0])} into DatosAjuste;
        insert javafx.scene.chart.LineChart.Data{xValue:maX yValue:(maX*constantesAjuste[1]+constantesAjuste[0])} into DatosAjuste;
        lineChart.data=[];
        if(do==1){
        insert javafx.scene.chart.LineChart.Series {data:DatosAjuste fill:Color.RED} into lineChart.data;
        }
    }
}
    public var seleccionarX: ChoiceBox = ChoiceBox {
                items: []
                layoutX: bind xMouse
                layoutY: bind yMouse
                visible: false;
                onMouseExited: function(event): Void {
                    seleccionarX.visible = false
                }
            }
    public var seleccionarY: ChoiceBox = ChoiceBox {
                items: []
                layoutX: bind xMouse
                layoutY: bind yMouse
                visible: false;
                onMouseExited: function(event): Void {
                    seleccionarY.visible = false
                }
            }
    def escuchaselX = bind seleccionarX.selectedIndex on replace {
                seleccionarX.visible = false;
                lineChart.data=[];
                detallesAjuste.visible=false;
                addDatos(conversorCanalIndice[seleccionarX.selectedIndex], yInt, "Gráfico",0);
            }
    def escuchaselY = bind seleccionarY.selectedIndex on replace {
                seleccionarX.visible = false;
                lineChart.data=[];
                detallesAjuste.visible=false;
                addDatos(xInt, conversorCanalIndice[seleccionarY.selectedIndex], "Gráfico",0);
            };
    public-read def toggleGroup: javafx.scene.control.ToggleGroup = javafx.scene.control.ToggleGroup {
    }
    public var toggleZoom: ToggleButton = ToggleButton {
        layoutX: bind (scatterChart.width-toggleZoom.width)
        layoutY: 5
        text: "Zoom In"
        selected:false
        toggleGroup:toggleGroup
    }
    public var toggleFit: ToggleButton = ToggleButton {
        layoutX: bind (scatterChart.width-toggleFit.width-toggleZoom.width-toggleDesplazar.width-20)
        layoutY: 5
        text: "Ajuste Lineal"
        selected:false
        toggleGroup:toggleGroup
    }
    public var toggleDesplazar: ToggleButton = ToggleButton {
        layoutX: bind (scatterChart.width-toggleZoom.width-toggleDesplazar.width-10)
        layoutY: 5
        text: "Desplazar"
        selected:true
        toggleGroup:toggleGroup
    }
    def cambiaCursorZoom=bind toggleZoom.selected on replace{
        if(toggleZoom.selected){
            scatterChart.customBackgroundContent.cursor=Cursor.CROSSHAIR;
        }
    }
    def cambiaCursorFit=bind toggleFit.selected on replace{
        if(toggleFit.selected){
            scatterChart.customBackgroundContent.cursor=Cursor.DEFAULT;
        }
    }
    def cambiaCursorDesplazar=bind toggleDesplazar.selected on replace{
        if(toggleDesplazar.selected){
            scatterChart.customBackgroundContent.cursor=Cursor.HAND;
        }
    }
    public override function create(): Node {
        
        return Group {
                    content: [
                        scatterChart, seleccionarX, seleccionarY,toggleZoom,toggleDesplazar,toggleFit,zona,lineChart,detallesAjuste,infoPuntero
                    ]
                };
    }
    public function addInfo(parametros: parametrosAnalogo) {
        Medicion.parametros.clonar(parametros);
    }
    public function addDatos(i: Integer, j: Integer, tit: String,tipo:Integer): Void {
        //Si es analogo
        if(tipo==0){
        titulo = tit;
        var datosSerie: Data[] = [];
        var Counter: Integer = 0;
        xInt = i;
        yInt = j;
        for (dat in Medicion.Datos[i].Datos) {
            insert Data { xValue: dat yValue: Medicion.Datos[j].Datos[Counter] } into datosSerie;
            Counter++;
        }
        if (i == 3) {
            numberAxisX.lowerBound = 0;
            numberAxisX.upperBound = Medicion.Datos[i].Datos[Counter - 1];
            numberAxisX.label = "{Medicion.parametros.unidadesPalabra()}";
        } else {
            numberAxisX.lowerBound = Medicion.parametros.canalSensor[i].rangoMin;
            numberAxisX.upperBound = Medicion.parametros.canalSensor[i].rangoMax;
            numberAxisX.label = "{Medicion.parametros.canalSensor[i].unidades}";
        }
        if (j == 3) {
            numberAxisY.lowerBound = 0;
            numberAxisY.upperBound = Medicion.Datos[j].Datos[Counter - 1];
            numberAxisY.label = "{Medicion.parametros.unidadesPalabra()}";
        } else {
            numberAxisY.lowerBound = Medicion.parametros.canalSensor[j].rangoMin;
            numberAxisY.upperBound = Medicion.parametros.canalSensor[j].rangoMax;
            numberAxisY.label = "{Medicion.parametros.canalSensor[j].unidades}";
        }
        Datos = datosSerie;
        DatosTotales=datosSerie;
        if (nolohice) {
            for (c in [0..2]) {
                if (Medicion.parametros.canalActivo[c]) {
                    insert (Medicion.parametros.canalSensor[c] as sensorAN).nombre into seleccionarX.items;
                    insert (Medicion.parametros.canalSensor[c] as sensorAN).nombre into seleccionarY.items;
                    conversorCanalIndice[seleccionarX.items.size() - 1] = c;
                }
            }
            insert "Tiempo" into seleccionarX.items;
            insert "Tiempo" into seleccionarY.items;
        }

        conversorCanalIndice[seleccionarX.items.size() - 1] = 3;
        //seleccionarX.select(xInt);
        //seleccionarY.select(yInt);
        scatterChart.xAxis.onMouseClicked = function(event: MouseEvent): Void {
                    xMouse = event.x;
                    yMouse = scatterChart.yAxis.height + event.y;
                    seleccionarX.visible = true;

                };
        scatterChart.yAxis.onMouseClicked = function(event: MouseEvent): Void {
                    xMouse = event.x;
                    yMouse = event.y;
                    seleccionarY.visible = true;
                };
        nolohice = false;
    //scatterChart.parent.pickOnBounds=true;
}
        //Si es digital
        else if(tipo==1){
        var counterDat=0;
        titulo = tit;
        xInt = i;
        yInt = j;
        var sens:sensorDIG=(MedicionDig.parametros.canalSensor[i] as sensorDIG);
        var datosSerie:Data[]=sacaVel(MedicionDig.Datos[i],sens.tipoInterrupcion,sens.regleta);
        var xMin:Number;
        var xMax:Number;
        var yMax:Number;
        var yMin:Number;
        var recorrer=true;
        for(dat in datosSerie){
            if(recorrer){
                xMin=dat.xValue;
                xMax=dat.xValue;
                yMin=dat.yValue;
                yMax=dat.yValue;
                recorrer=false;}
            if(dat.xValue<=xMin){xMin=dat.xValue;}
            else if(dat.xValue>=xMax){xMax=dat.xValue;}
            if(dat.yValue<=yMin){yMin=dat.yValue;}
            else if(dat.yValue>=yMax){yMax=dat.yValue;}
            counterDat++;
        }
        numberAxisX.lowerBound = xMin-(xMax-xMin)/(counterDat+1);
        numberAxisX.upperBound = xMax+(xMax-xMin)/(counterDat+1);
        numberAxisX.label = "Tiempo";
        numberAxisY.lowerBound = yMin-(yMax-yMin)/(counterDat+1);
        numberAxisY.upperBound = yMax+(xMax-xMin)/(counterDat+1);
        numberAxisY.label = "Velocidad canal {i+1}";
        Datos=[];
        DatosTotales=[];
        for (dat in datosSerie){ 
        insert dat into Datos;
        insert dat into DatosTotales;}
        if (nolohice) {
            for (c in [0..3]) {
                if (MedicionDig.parametros.canalActivo[c]) {
                    insert "{(MedicionDig.parametros.canalSensor[c] as sensorDIG).nombre} {c+1}" into seleccionarX.items;
                    insert "{(MedicionDig.parametros.canalSensor[c] as sensorDIG).nombre} {c+1}" into seleccionarY.items;
                    conversorCanalIndice[c] = c;
                }
            }
        }
        scatterChart.xAxis.onMouseClicked = function(event: MouseEvent): Void {
                    xMouse = event.x;
                    yMouse = scatterChart.yAxis.height + event.y;
                    seleccionarX.visible = true;

                };
        scatterChart.yAxis.onMouseClicked = function(event: MouseEvent): Void {
                    xMouse = event.x;
                    yMouse = event.y;
                    seleccionarY.visible = true;
                };
        nolohice = false;
}
        else if (tipo==2){
                    var counterDat=0;
        titulo = tit;
        xInt = i;
        yInt = j;
        var sens:sensorDIG=(MedicionDig.parametros.canalSensor[i] as sensorDIG);
        var datosSerie:Data[]=sacaPos(MedicionDig.Datos[i],sens.tipoInterrupcion,sens.regleta);
        var xMin:Number;
        var xMax:Number;
        var yMax:Number;
        var yMin:Number;
        var recorrer=true;
        for(dat in datosSerie){
            if(recorrer){
                xMin=dat.xValue;
                xMax=dat.xValue;
                yMin=dat.yValue;
                yMax=dat.yValue;
                recorrer=false;}
            if(dat.xValue<=xMin){xMin=dat.xValue;}
            else if(dat.xValue>=xMax){xMax=dat.xValue;}
            if(dat.yValue<=yMin){yMin=dat.yValue;}
            else if(dat.yValue>=yMax){yMax=dat.yValue;}
            counterDat++;
        }
        numberAxisX.lowerBound = xMin-(xMax-xMin)/(counterDat+1);
        numberAxisX.upperBound = xMax+(xMax-xMin)/(counterDat+1);
        numberAxisX.label = "Tiempo";
        numberAxisY.lowerBound = yMin-(yMax-yMin)/(counterDat+1);
        numberAxisY.upperBound = yMax+(xMax-xMin)/(counterDat+1);
        numberAxisY.label = "Posición canal {i+1}";
        Datos=[];
        DatosTotales=[];
        for (dat in datosSerie){
        insert dat into Datos;
        insert dat into DatosTotales;}
        if (nolohice) {
            for (c in [0..3]) {
                if (MedicionDig.parametros.canalActivo[c]) {
                    insert "{(MedicionDig.parametros.canalSensor[c] as sensorDIG).nombre} {c+1}" into seleccionarX.items;
                    insert "{(MedicionDig.parametros.canalSensor[c] as sensorDIG).nombre} {c+1}" into seleccionarY.items;
                    conversorCanalIndice[c] = c;
                }
            }
        }
        scatterChart.xAxis.onMouseClicked = function(event: MouseEvent): Void {
                    xMouse = event.x;
                    yMouse = scatterChart.yAxis.height + event.y;
                    seleccionarX.visible = true;

                };
        scatterChart.yAxis.onMouseClicked = function(event: MouseEvent): Void {
                    xMouse = event.x;
                    yMouse = event.y;
                    seleccionarY.visible = true;
                };
        nolohice = false;
        }


    }
    public function addDatosTabla(datos:Data[],xHeader:String,yHeader:String):Void{
        var xMin:Number;
        var xMax:Number;
        var yMin:Number;
        var yMax:Number;
        var counterDat=0;
        Datos=[];
        DatosTotales=[];
        var recorrer=true;
        for (d in datos){
             if(recorrer){
                xMin=d.xValue;
                xMax=d.xValue;
                yMin=d.yValue;
                yMax=d.yValue;
                recorrer=false;}
            xMin=Math.min(d.xValue, xMin);
            yMin=Math.min(d.yValue, yMin);
            xMax=Math.max(d.xValue, xMax);
            yMax=Math.max(d.yValue, yMax);
            insert d into DatosTotales;
            insert d into Datos;
            counterDat++;
        }
        numberAxisX.lowerBound = xMin-(xMax-xMin)/(counterDat+1);
        numberAxisX.upperBound = xMax+(xMax-xMin)/(counterDat+1);
        numberAxisX.label = xHeader;
        numberAxisY.lowerBound = yMin-(yMax-yMin)/(counterDat+1);
        numberAxisY.upperBound = yMax+(xMax-xMin)/(counterDat+1);
        numberAxisY.label = yHeader;
    }
    public function sacaVel(tiempos:ArregloDatos,tipo:Boolean,regleta:Integer):Data[]{
        var vels:Data[]=[];
        var counterVel=0;
        var tAnterior:Double;
        var tInicial:Double;
        for(t in tiempos.Datos){
            if (counterVel==0){
                tInicial=t;
                }
            if (tipo) {
                    if (counterVel > 0) {
                        var vel = ((regleta)) / ((t - tAnterior) / 1000);
                        var tiempo= (t+tAnterior-tInicial)/2000000;
                        insert Data { xValue: tiempo yValue: vel } into vels;
                    }
                    tAnterior=t;
                }
                else
                {
                    if (counterVel == 1) {
                        var vel = ((regleta)) / ((t - tAnterior) / 1000);
                        var tiempo= (t+tAnterior-tInicial)/2000000;
                        insert Data { xValue: tiempo yValue: vel } into vels;
                        counterVel = -1;
                    }
                    tAnterior=t;

                }
        counterVel++;
        }

        return vels;
    }
    public function sacaPos(tiempos:ArregloDatos,tipo:Boolean,regleta:Integer):Data[]{
        var poss:Data[]=[];
        var pos=0.0;
        var tiempo:Double=0.0;
        for(t in tiempos.Datos){
                        pos += (regleta as Double)/1000;
                        tiempo= (t)/2000000;
                        insert Data { xValue: tiempo yValue: pos } into poss;
                }
        return poss;
    }
    }
